package com.coolwen.controller;

import com.coolwen.entity.Upload;
import com.coolwen.service.upload.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Nieyu on 2016/11/27.
 */
@Controller
@RequestMapping(value = "/sql")
public class BackupSql {

    @Autowired
    UploadService uploadService;

    private String binName = "C:\\Program Files\\mysql-5.6.24-win32\\bin";

    @RequestMapping(value = "/backup", method = RequestMethod.GET)
    public String uploadSql(Model model, HttpServletRequest request) throws IOException {

        try {
            Runtime rt = Runtime.getRuntime();
            // 调用 调用mysql的安装目录的命令
            Process child = rt
                    .exec("C:\\Program Files\\mysql-5.6.24-win32\\bin\\mysqldump -h 172.16.10.80 -uroot -ppassword123 judge_system");
            // 把进程执行中的控制台输出信息写入.sql文件，即生成了备份文件。
            InputStream in = child.getInputStream();
            InputStreamReader xx = new InputStreamReader(in, "utf-8");
            // 设置输出流编码为utf-8。这里必须是utf-8，否则从流中读入的是乱码
            String inStr;
            StringBuffer sb = new StringBuffer("");
            String outStr;
            // 组合控制台输出信息字符串
            BufferedReader br = new BufferedReader(xx);
            while ((inStr = br.readLine()) != null) {
                sb.append(inStr + "\r\n");
            }
            outStr = sb.toString();

            SimpleDateFormat dt = new SimpleDateFormat("yyyyMMdd");
            String date = dt.format(new Date());//获取当前时间
            // 要用来做导入用的sql目标文件：
            FileOutputStream fout = new FileOutputStream(
                    "d:/"+new String(date.getBytes("GB2312"), "8859_1")+".sql");
            OutputStreamWriter writer = new OutputStreamWriter(fout, "utf-8");
            writer.write(outStr);
            writer.flush();
            in.close();
            xx.close();
            br.close();
            writer.close();
            fout.close();
//            System.out.println("");
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("error", "备份成功！");
        return "errorPage/format_error";
    }
    /**
     * 上传sql文件
     *
     * @param model
     * @param request
     * @param md5
     * @return
     */
    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public String uploadSQL(Model model, HttpServletRequest request, String md5) {

        model.addAttribute("md5", md5);

        return "page/upload_sql";
    }

    @RequestMapping(value = "/uploadSqls", method = RequestMethod.POST)
    public String uploadSqls(Model model, HttpServletRequest request) throws IOException {

        Upload upload = new Upload();

        String md = request.getParameter("md5");

        List<Upload> uploads = uploadService.selectByMd5(md);

        if (uploads.isEmpty()) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            String logoPathDir = "/resources/upload";

            String logoRealPathDir = request.getSession().getServletContext().getRealPath(logoPathDir);

            File logoSaveFile = new File(logoRealPathDir);
            if (!logoSaveFile.exists())
                logoSaveFile.mkdirs();
            /** 页面控件的文件流* */
            MultipartFile multipartFile = multipartRequest.getFile("files");
            /** 获取文件的后缀* */
            String suffix = multipartFile.getOriginalFilename().substring(
                    multipartFile.getOriginalFilename().lastIndexOf("."));
            /** 使用UUID生成文件名称* */
            String logImageName = UUID.randomUUID().toString() + suffix;// 构建文件名称
            /** 拼成完整的文件保存路径加文件* */
            String fileName = logoRealPathDir + File.separator + logImageName;
            File file = new File(fileName);
            try {
                multipartFile.transferTo(file);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            /** 打印出上传到服务器的文件的绝对路径* */
//        System.out.println("****************"+fileName+"**************");
            if (!suffix.equals(".sql")) {
                model.addAttribute("error", "上传失败，请上传SQL类型的文件！");
                return "errorPage/format_error";
            } else {
                try {
                    Runtime rt = Runtime.getRuntime();

                    // 调用 mysql 的 cmd:
                    Process child = rt.exec(binName + "mysql.exe -uroot -ppassword123 judge_system ");
                    OutputStream out = child.getOutputStream();//控制台的输入信息作为输出流
                    String inStr;
                    StringBuffer sb = new StringBuffer("");
                    String outStr;
                    BufferedReader br = new BufferedReader(new InputStreamReader(
                            new FileInputStream(fileName), "utf8"));
                    while ((inStr = br.readLine()) != null) {
                        sb.append(inStr + "\r\n");
                    }
                    outStr = sb.toString();

                    OutputStreamWriter writer = new OutputStreamWriter(out, "utf8");
                    writer.write(outStr);
                    // 注：这里如果用缓冲方式写入文件的话，会导致中文乱码，用flush()方法则可以避免
                    writer.flush();
                    // 别忘记关闭输入输出流
                    out.close();
                    br.close();
                    writer.close();

                    upload.setMd5(md);
                    uploadService.insertSelective(upload);

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            return "upload/upload_successful";
        } else {
            return "errorPage/upload_error";
        }
    }
}
